<template>
	<div class="layout-container layout-pd w100">
		<div class="box top-box">
			<cardItem v-for="(item, index) in cardData" :key="index">
				<!--title-->
				<template #title> {{ item.text }} </template>

				<!--icon-->
				<template #icon>
					<svg
						t="1711422868577"
						class="icon"
						viewBox="0 0 1024 1024"
						version="1.1"
						xmlns="http://www.w3.org/2000/svg"
						p-id="1641"
						width="30"
						height="30"
					>
						<path d="M96.997 334.088l679.994-182.195 121.81 454.62-679.994 182.195z" fill="#C3D2FB" p-id="1642"></path>
						<path d="M159 317.45h768v554.67H159z" fill="#386BF3" p-id="1643"></path>
						<path d="M750.012186 658.503745a64 64 0 1 0 12.608444-127.377498 64 64 0 1 0-12.608444 127.377498Z" fill="#3D4265" p-id="1644"></path>
					</svg>
				</template>

				<template #amount> {{ item.isAmount ? $amountFormat(item.value) : item.value }} </template>

				<!--底部-->
				<template #bottom>
					<div>
						{{ item.subText }}: <span>{{ item.isAmount ? $amountFormat(item.subValue) : item.subValue }}</span>
					</div>
				</template>
			</cardItem>
		</div>

		<!--图表盒子-->
		<div class="box chart-box mr-top">
			<chart-line :state="chartRevenue" />

			<chart-line :state="chartOrder" />

			<chart-line :state="chartOrderRefund" />

			<!--订单状态-->
			<schedule-percentage :state="stateSchedulePercentage" />

			<chart-line :state="chartUserGrowth" />

			<chart-line :state="chartUserVisitor" />
		</div>

		<!--实时滚动订单-->
		<div class="box scroll-box mr-top">
			<!--使用双表格，header-table样式隐藏表格内容部分，footer-table样式隐藏表格表头部分-->
			<el-table class="header-table" border :data="orderList" :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle">
				<el-table-column :label="$t('Order.OrderId')" prop="id" show-overflow-tooltip>
					<template #default="{ row }">
						<span class="link" @click="jumpPage('/bizs/Order/index', { orderId: row.id })">{{ row.id }}</span>
					</template>
				</el-table-column>

				<el-table-column :label="$t('Order.userInfo')" prop="userNickname" show-overflow-tooltip>
					<template #default="{ row }">
						<card-info-col :icon="row.userAvatar" :name="row.userNickname" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.shopInfo')" prop="shopName" show-overflow-tooltip>
					<template #default="{ row }">
						<card-info-col :icon="row.shopAvatar" :name="row.shopName" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('Order.actualAmount')" prop="actualAmount" show-overflow-tooltip>
					<template #default="{ row }">
						{{ $amountFormat(row.actualAmount) }}
					</template>
				</el-table-column>
				<el-table-column prop="createTime" :label="$t('Order.createTime')" show-overflow-tooltip />
			</el-table>

			<vue3-seamless-scroll class="seamless-warp" hover-stop="true" :hover="true" :list="orderList">
				<el-table class="footer-table" border :data="orderList" :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle">
					<el-table-column :label="$t('Order.OrderId')" prop="id" show-overflow-tooltip>
						<template #default="{ row }">
							<span class="link" @click="jumpPage('/bizs/Order/index', { orderId: row.id })">{{ row.id }}</span>
						</template>
					</el-table-column>

					<el-table-column :label="$t('Order.userInfo')" prop="userNickname" show-overflow-tooltip>
						<template #default="{ row }">
							<card-info-col :icon="row.userAvatar" :name="row.userNickname" />
						</template>
					</el-table-column>
					<el-table-column :label="$t('Order.shopInfo')" prop="shopName" show-overflow-tooltip>
						<template #default="{ row }">
							<card-info-col :icon="row.shopAvatar" :name="row.shopName" />
						</template>
					</el-table-column>
					<el-table-column :label="$t('Order.actualAmount')" prop="actualAmount" show-overflow-tooltip>
						<template #default="{ row }">
							{{ $amountFormat(row.actualAmount) }}
						</template>
					</el-table-column>
					<el-table-column prop="createTime" :label="$t('Order.createTime')" show-overflow-tooltip />
				</el-table>
			</vue3-seamless-scroll>
		</div>

		<!--排行榜-->
		<div class="box rank-box mr-top">
			<!--代理-->
			<div class="item">
				<div class="rank_top">
					<div>{{ $t('Dashboard.ProductRanking') }}</div>
					<div>{{ $t('Dashboard.sale') }}</div>
				</div>
				<el-divider />
				<el-empty v-if="rank.prodList.length == 0" style="padding-bottom: 16px" />
				<div class="rank_content" v-for="(item, index) in rank.prodList" :key="item.id" :class="{ rank_content_line: index != 0 }">
					<div class="rank_left">
						<div class="rank_img">
							<avatar :src="item.pic" />
							<span class="rank_sign" :class="{ rank_sign1: index == 0, rank_sign2: index == 1, rank_sign3: index == 2 }">
								{{ index + 1 }}
							</span>
						</div>
						<div class="rank_cen">
							<div class="rank_title">{{ item.name }}</div>
							<div class="rank_text ellipsis">{{ item.brief }}</div>
						</div>
					</div>
					<div class="rank_sum">{{ item.saleNum }}</div>
				</div>
			</div>
			<!--店铺-->
			<div class="item">
				<div class="rank_top">
					<div>{{ $t('Dashboard.storeRanKing') }}</div>
					<div>{{ $t('Dashboard.sale') }}</div>
				</div>
				<el-divider />
				<el-empty v-if="rank.shopList.length == 0" style="padding-bottom: 16px" />
				<div class="rank_content" v-for="(item, index) in rank.shopList" :key="item.id" :class="{ rank_content_line: index != 0 }">
          <div class="rank_left">
						<div class="rank_img">
							<avatar :src="item.avatar" />
							<span class="rank_sign" :class="{ rank_sign1: index == 0, rank_sign2: index == 1, rank_sign3: index == 2 }">
								{{ index + 1 }}
							</span>
						</div>
            <div class="rank_cen">
							<div class="rank_title">{{ item.name }}</div>
							<div class="rank_text ellipsis">{{ item.address }}</div>
						</div>
					</div>
					<div class="rank_sum">{{ item.saleNum }}</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup lang="ts">
import cardItem from './components/card-item.vue';
import ChartLine from '/@/views/bizs/Dashboard/components/chart-line.vue';
import { Chart } from '/@/hooks/chart';
import SchedulePercentage from '/@/views/bizs/Dashboard/components/schedule-percentage.vue';
import { SchedulePercentageProps } from '/@/views/bizs/Dashboard/components/schedulePercentage';
import Avatar from '/@/components/biz/avatar.vue';
// 引入无缝滚动组件
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';
import { useTable } from '/@/hooks/table';
import CardInfoCol from '/@/components/biz/card-info-col.vue';
import { useI18n } from 'vue-i18n';
import { statisticsAPI, getRankingListAPI, getLatestOrderAPI, getChartDataAPI, getStateOrdersAPI } from '/@/api/bizs/dashboard';
import {getAround7RangeTime} from "/@/utils/date";

const { t } = useI18n();

const cardData = ref([
	{
		key: 'incomeToday',
		subKey: 'incomeTotal',
		text: t('Dashboard.TodaySEarnings'),
		subText: t('Dashboard.accumulatedEarnings'),
		value: 0,
		subValue: 0,
		isAmount: true,
	},
	{
		key: 'orderToday',
		subKey: 'orderTotal',
		text: t('Dashboard.todayOrder'),
		subText: t('Dashboard.CumulativeOrder'),
		value: 0,
		subValue: 0,
	},
	{
		key: 'userToday',
		subKey: 'userTotal',
		text: t('Dashboard.TodayUser'),
		subText: t('Dashboard.CumulativeUser'),
		value: 0,
		subValue: 0,
	},
	{
		key: 'prodToday',
		subKey: 'prodTotal',
		text: t('Dashboard.todayProduct'),
		subText: t('Dashboard.CumulativeProduct'),
		value: 0,
		subValue: 0,
	},
]);

const dateTime = getAround7RangeTime().join(',');

const chartRevenue = reactive<Chart>({
	title: t('Dashboard.Income'),
	type: 'line',
	id: 'chartRevenue',
	options: {},
	params: {
		type: 1,
		rangeTime: [],
	},
	fetch: getChartDataAPI,
	isAmount: true,
});

const chartOrder = reactive<Chart>({
	title: t('Dashboard.Order'),
	type: 'line',
	id: 'chartOrder',
	options: {},
	params: {
		type: 2,
		rangeTime: [],
	},
	fetch: getChartDataAPI,
});

const chartOrderRefund = reactive<Chart>({
	title: t('Dashboard.OrderRefund'),
	type: 'line',
	id: 'chartOrderRefund',
	options: {},
	params: {
		type: 3,
		rangeTime: [],
	},
	fetch: getChartDataAPI,
});

const chartUserGrowth = reactive<Chart>({
	title: t('Dashboard.UserGrowth'),
	type: 'line',
	id: 'chartUserGrowth',
	options: {},
	params: {
		type: 4,
		rangeTime: [],
	},
	fetch: getChartDataAPI,
});

const chartUserVisitor = reactive<Chart>({
	title: t('Dashboard.UserAccess'),
	type: 'line',
	id: 'chartUserVisitor',
	options: {},
	params: {
		type: 5,
		rangeTime: [],
	},
	fetch: getChartDataAPI,
});

// 颜色组
const colors = reactive(['#129cff', '#00daf2', '#12a3d0', '#b9daf2', '#00b9f2', '#baf2e9', '#0079da']);

const stateSchedulePercentage = reactive<SchedulePercentageProps>({
	title: t('Dashboard.OrderStatus'),
	params: {
		rangeTime: [],
	},
	fetch: undefined,

	data: [
		{
			color: colors[0],
			label: t('Order.NonPayment'),
			value: 0,
			percentage: 0,
			width: '',
		},
		{
			color: colors[1],
			label: t('Order.unshipped'),
			value: 0,
			percentage: 0,
			width: '',
		},
		{
			color: colors[2],
			label: t('Order.NotReceiveTheGoods'),
			value: 0,
			percentage: 0,
			width: '',
		},
		{
			color: colors[3],
			label: t('Order.unrated'),
			value: 0,
			percentage: 0,
			width: '',
		},
		{
			color: colors[4],
			label: t('Order.completed'),
			value: 0,
			percentage: 0,
			width: '',
		},
		{
			color: colors[5],
			label: t('Order.Lose'),
			value: 0,
			percentage: 0,
			width: '',
		},
	],
});

const orderList = ref([]);
//  table hook
const { tableStyle } = useTable({});

const router = useRouter();
const jumpPage = (path: string, query?: any) => {
	router.push({ path: path, query: query ? query : null });
};

// 排行榜
const rank = reactive({
	prodList: [],
	shopList: [],
});

// 获取统计数据
const getStatisticsData = async () => {
	const res = await statisticsAPI();
	if (res.code === 0) {
		cardData.value = cardData.value.map((item) => {
			return {
				...item,
				value: res.data[item.key],
				subValue: res.data[item.subKey],
			};
		});
	}
};

/**
 * 获取排行榜
 * @param type 1产品  2 店铺
 */
const getRankingListFn = async (type: number) => {
	const res = await getRankingListAPI({
		type: type,
	});

	if (res.code === 0) {
		if (type == 1) {
			rank.prodList = res.data;
		} else {
			rank.shopList = res.data;
		}
	}
};

// 获取最新订单
const getLatestOrderFn = async () => {
	const res = await getLatestOrderAPI({ limit: 10 });
	if (res.code === 0) {
		orderList.value = res.data;
	}
};

// 获取订单状态数据
const getStateOrdersFn = async () => {
	const res = await getStateOrdersAPI();
	if (res.code === 0) {
		const total = res.data.total;

		stateSchedulePercentage.data![0].value = res.data.unpay;
		stateSchedulePercentage.data![0].percentage = total !== 0 ? (res.data.unpay / total) * 100 : 0;

		stateSchedulePercentage.data![1].value = res.data.paid;
		stateSchedulePercentage.data![1].percentage = total !== 0 ? (res.data.paid / total) * 100 : 0;

		stateSchedulePercentage.data![2].value = res.data.consignment;
		stateSchedulePercentage.data![2].percentage = total !== 0 ? (res.data.consignment / total) * 100 : 0;

		stateSchedulePercentage.data![3].value = res.data.confirm;
		stateSchedulePercentage.data![3].percentage = total !== 0 ? (res.data.confirm / total) * 100 : 0;

		stateSchedulePercentage.data![4].value = res.data.completed;
		stateSchedulePercentage.data![4].percentage = total !== 0 ? (res.data.completed / total) * 100 : 0;

		stateSchedulePercentage.data![5].value = res.data.cancel;
		stateSchedulePercentage.data![5].percentage = total !== 0 ? (res.data.cancel / total) * 100 : 0;
	}
};

onMounted(async () => {
	await getStatisticsData();
	await getLatestOrderFn();
	await getStateOrdersFn();
	await getRankingListFn(1); // 获取产品排行榜
	await getRankingListFn(2); // 获取店铺排行榜
});
</script>

<style lang="scss" scoped>
// 边框角度
$borderRadius: 10px;

.mr-top {
	margin-top: 20px;
}

.box {
	width: 100%;
}

.top-box {
	display: flex;
	gap: 20px;
}

.chart-box {
	display: grid;
	grid-template-columns: repeat(3, minmax(415px, 1fr));
	grid-gap: 20px;

	& > div {
		width: 100%;
		background-color: #fff;
		//height: 400px;
		border-radius: 10px;
		padding: 20px;
	}
}

.scroll-box {
	.link {
		color: #1890ff;
		cursor: pointer;
	}

	:deep(.seamless-warp) {
		height: 100%;
		max-height: 720px !important;
		overflow: hidden;
	}

	:deep(.header-table .el-table__body-wrapper) {
		display: none;
	}

	:deep(.footer-table .el-table__header-wrapper) {
		display: none;
		width: 100%;
	}
}

// 排行榜
.rank-box {
	display: flex;
	gap: 20px;

	margin-top: 26px;
	margin-bottom: 16px;

	.item {
		width: 50%;
		min-width: 536px;
		border-radius: $borderRadius;
		background: #ffffff;
		box-shadow: 4px 6px 26px 0px rgba(0, 0, 0, 0.06);

		:deep(.el-divider--horizontal) {
			margin: 0;
		}

		.rank_top {
			padding: 10px 26px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.rank_top_btn {
				min-width: 180px;
				height: 36px;
				background: #f2f5fa;
				border-radius: 5px;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 2px;
			}
			.rank_top_btn span {
				display: block;
				width: 88px;
				height: 32px;
				line-height: 31px;
				font-size: 14px;
				font-weight: 500;
				text-align: center;
				color: #39404d;
				cursor: pointer;
			}
			.active1 {
				background: #ffffff;
				border-radius: 4px;
				box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.1);
			}
		}
		.rank_top div {
			font-size: 16px;
			font-weight: 600;
			text-align: left;
			color: #39404d;
		}
		.rank_content_line {
			border-top: 1px solid #e4e4e6;
		}
		.rank_content {
			display: flex;
			justify-content: space-between;
			padding: 0 26px;
      box-sizing: border-box;

      .rank_left {
        display: flex;
        width: calc(100% - 100px);

        .rank_img {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          margin: 12px 0;
          position: relative;

          .rank_sign {
            position: absolute;
            left: -2px;
            top: -2px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            font-size: 12px;
            font-weight: 600;
            text-align: center;
            color: #000000;
            background: #ececee;
          }
          .rank_sign1 {
            background: #fde253 !important;
          }
          .rank_sign2 {
            background: #bbcef2 !important;
          }
          .rank_sign3 {
            background: #deb18f !important;
          }
        }

        .rank_cen {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin: 10px 0;

          .rank_title {
            font-size: 16px;
            font-weight: 600;
            text-align: left;
            color: #39404d;
            line-height: 20px;
            margin: 10px 10px 4px 10px;
            word-break: keep-all;
          }
          .rank_text {
            width: 100%;
            font-size: 14px;
            font-weight: 400;
            text-align: left;
            color: #889dbb;
            line-height: 16px;
            margin: 0px 10px 10px 10px;
            word-break: keep-all;
          }

        }

      }
			.rank_sum {
				font-weight: bold;
				color: #333333;
				font-size: 20px;
				margin: auto 0;
			}
		}
	}
}
</style>
